import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token";

const state = {
    code: '',
    token: getToken(),
    userInfo: {}
};
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //正常情况下是把验证码发到手机号,这里是直接返回
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        console.log(result);
        if (result.code == 200) {
            // console.log('ok');
            return 'ok'
        } else {
            // console.log('error');
            return Promise.reject(new Error('faile'))
        }
    },
    //登录 token
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
            //用户已经登录获取到token
            commit("USERLOGIN", result.data.token)
            //持久化存储token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取登录信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        // console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //退出登录
    async userLogout({ commit }) {
        const result = await reqLogout()
        if (result.code == 200) {
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
};
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //退出登录,清除本地数据
    CLEAR(state) {
        removeToken()
        state.token = ''
        state.userInfo = {}
    }
};
const getters = {};

export default {
    state, mutations, actions, getters
}